package edu.zust.zw.shop.controller;

import java.io.UnsupportedEncodingException;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.util.StringUtil;

import edu.zust.zw.shop.service.LoginService;
import edu.zust.zw.shop.service.UserService;
import edu.zust.zw.shop.util.PersonStringUtil;
import edu.zust.zw.shop.util.Result;

@RequestMapping("/login")
@RestController
@Transactional
public class LoginController extends BaseController {

    @Autowired
    private LoginService loginService;
    @Autowired
    private UserService usrService;
    
    @GetMapping("/login")
    public Result login(String userId, String loginPass, String key) {
        if (StringUtil.isEmpty(userId) || StringUtil.isEmpty(loginPass) || StringUtil.isEmpty(key)) {
            return Result.error(Result.Code.PARAMETER_ERROR);
        }
        if (loginService.login(userId, loginPass, key)) {
            getSession(getRequest()).setAttribute("userInfo", usrService.getUserInfo(userId));
            return Result.success();
        }
        return Result.error(Result.Code.NO_LOGIN, "登陆失败");
    }
    
    @PostMapping("/add")
    public Result add(String userId, String username, String email, String password) {
        if (PersonStringUtil.containsEmpty(userId, username, email, password)) {
            return Result.error(Result.Code.PARAMETER_ERROR);
        }
        
        if (!loginService.checkAccount(userId)) {
            try {
                return Result.error(Result.Code.NO_UPDATE, new String("注册失败, 注册账号已经存在".getBytes("ISO-8859-1"), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            };
        }
        
        if (!loginService.checkUsername(username)) {
            return Result.error(Result.Code.NO_UPDATE, "注册失败, 注册用户名已经存在");
        }
        
        if (!loginService.add(userId, username, email, password)) {
            return Result.error(Result.Code.NO_UPDATE, "注册失败");
        }
        
        return Result.success();
    }

}
